package com.spark.tags;


import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.spark.core.SparkContext;
import com.spark.core.XMap;

public class DataSet extends Component {
	
	private static final String DEFAULT_TEMPLATES = "dataSet.ftl";
	
	public static final String PROPERTITY_FIELDS = "fields";
	public static final String PROPERTITY_MAP = "map";
	public static final String PROPERTITY_MAPPING = "mapping";
	public static final String PROPERTITY_RETURN_FIELD = "returnField";
	public static final String PROPERTITY_VALUE_FIELD = "valueField";
	public static final String PROPERTITY_DISPLAY_FIELD = "displayField";
	public static final String PROPERTITY_DISPLAY_RENDERER = "displayRenderer";
	public static final String PROPERTITY_MAP_FORM = "from";
	public static final String PROPERTITY_MAP_TO = "to";;
	public static final String PROPERTITY_DATAS = "datas";
	public static final String PROPERTITY_DATASOURCE = "source";
	public static final String PROPERTITY_AUTO_CREATE = "autoCreate";
	public static final String PROPERTITY_AUTO_QUERY = "autoQuery";
	public static final String PROPERTITY_BINDNAME = "bindName";
	public static final String PROPERTITY_MODEL = "model";
	public static final String PROPERTITY_LOADDATA = "loadData";
	public static final String PROPERTITY_PAGESIZE = "pageSize";	
	public static final String PROPERTITY_QUERYURL = "queryUrl";
	public static final String PROPERTITY_QUERYDATASET = "queryDataset";
	public static final String PROPERTITY_SUBMITURL = "submitUrl";
	public static final String PROPERTITY_SELECTABLE = "selectable";
	public static final String PROPERTITY_SELECTION_MODEL = "selectionModel";
	public static final String PROPERTITY_SELECT_FUNCTION = "selectFunction";
	public static final String PROPERTITY_CHECK_DIRTY = "checkDirty";
	public static final String PROPERTITY_NOT_FOUND_MESSAGE = "notFoundMessage";
	public static final String PROPERTITY_NOT_FOUND_CALLBACK = "notFoundCallback";
	public static final String PROPERTITY_SORT_MODEL = "sortModel";
	public static final String PROPERTITY_DEFAULT_SORT_FIELD = "defaultSortField";
	public static final String PROPERTITY_DEFAULT_SORT_TYPE = "defaultSortType";
	
	public static final String PROPERTITY_FIELD_REQUIRED = "required";
	public static final String PROPERTITY_FIELD_PERSISTED = "persisted";
	public static final String PROPERTITY_FIELD_DISABLED = "disabled";  
	public static final String PROPERTITY_FIELD_VALIDATOR = "validator";  
	public static final String PROPERTITY_FIELD_RESTRICT = "restrict";
	public static final String PROPERTITY_FIELD_VALID_MESSAGE = "validMessage";
	
	public static final String DEFAULT_SELECTION_MODEL = "multiple";
	
	public static final String PROPERTITY_LOCK = "lock";
	
	public static final String PROPERTITY_LOADING_TIP = "loadingTip";
	public static final String PROPERTITY_SUCCESS_TIP = "successTip";
	
	public String getTemplate(){
		return DEFAULT_TEMPLATES;
	}
	
	@SuppressWarnings("unchecked")
	public void init(XMap view, SparkContext context) throws Exception{
		super.init(view, context);
		context.putDataSet(view);
		XMap fields = view.getChild(PROPERTITY_FIELDS);
		List<XMap> fieldList = new ArrayList<XMap>();
		Map model = context.getModel();
		if(fields != null) {
			Iterator<XMap> fit = fields.getChildIterator();
			if(fit != null)
			while(fit.hasNext()){
				XMap field = (XMap)fit.next();
				
				//TODO:处理一些多语言
				if("true".equalsIgnoreCase(field.getString(PROPERTITY_FIELD_REQUIRED))) {
					field.putBoolean(PROPERTITY_FIELD_REQUIRED, true);
				}else {
					field.remove(PROPERTITY_FIELD_REQUIRED);
				}
				if("true".equalsIgnoreCase(field.getString(PROPERTITY_FIELD_PERSISTED))) {
					field.putBoolean(PROPERTITY_FIELD_PERSISTED, true);
				}else {
					field.remove(PROPERTITY_FIELD_PERSISTED);
				}
				if("true".equalsIgnoreCase(field.getString(PROPERTITY_FIELD_DISABLED))) {
					field.putBoolean(PROPERTITY_FIELD_DISABLED, true);
				}else {
					field.remove(PROPERTITY_FIELD_DISABLED);
				}
				
				
				
//				if(sdfc.getDefaultValue()!=null)field.putString(DataSetFieldConfig.PROPERTITY_DEFAULTVALUE, session.parseString(sdfc.getDefaultValue(), model));
//				String lovService = field.getString(Lov.PROPERTITY_LOV_SERVICE);
//				if(lovService!=null){
//					field.putString(Lov.PROPERTITY_LOV_SERVICE, uncertain.composite.TextParser.parse(lovService, model));
//				}
				String lovWidth = field.getString(Lov.PROPERTITY_LOV_WIDTH);
				if(lovWidth!=null){
					field.putInt(Lov.PROPERTITY_LOV_WIDTH, new Integer(lovWidth));
				}
				String lovHeight = field.getString(Lov.PROPERTITY_LOV_HEIGHT);
				if(lovWidth!=null){
					field.putInt(Lov.PROPERTITY_LOV_HEIGHT, new Integer(lovHeight));
				}
				
				XMap mapping = field.getChild(PROPERTITY_MAPPING);
				List<XMap> maplist = mapping!=null ? mapping.getChilds() : new ArrayList();
				String name = field.getString(PROPERTITY_NAME);
				String displayField = field.getString(PROPERTITY_DISPLAY_FIELD);
				String valueField = field.getString(PROPERTITY_VALUE_FIELD);
				String returnField = field.getString(PROPERTITY_RETURN_FIELD);
				
				boolean addReturn = true;
				boolean addDisplay = true;
				Iterator<XMap> mit = maplist.iterator();
				while(mit.hasNext()){
					XMap map = (XMap)mit.next();
					if(map.getString(PROPERTITY_MAP_TO).equals(returnField) && map.getString(PROPERTITY_MAP_FORM).equals(valueField)) {
						addReturn = false;
					}
					if(map.getString(PROPERTITY_MAP_TO).equals(name) && map.getString(PROPERTITY_MAP_FORM).equals(displayField)) {
						addDisplay = false;
					}
				}
				if(addDisplay && displayField!=null && name!=null){
					XMap rmap = new XMap(PROPERTITY_MAP);
					rmap.putString(PROPERTITY_MAP_FORM, displayField);
					rmap.putString(PROPERTITY_MAP_TO, name);
					maplist.add(rmap);
				}
				if(addReturn && returnField!=null && returnField!=null){
					XMap rmap = new XMap(PROPERTITY_MAP);
					rmap.putString(PROPERTITY_MAP_FORM, valueField);
					rmap.putString(PROPERTITY_MAP_TO, returnField);
					maplist.add(rmap);
				}
				if(maplist.size() > 0){
					field.put(PROPERTITY_MAPPING, maplist);
				}
				fieldList.add(field);
			}
			context.addJsonConfig(PROPERTITY_FIELDS, fieldList);
			
		}
		
		
		XMap cts = view.getChild(PROPERTITY_LOCK);
		if(cts != null) {
			List<String> locks = new ArrayList<String>();
			Iterator<XMap> fit = cts.getChildIterator();
			if(fit != null)
				while(fit.hasNext()){
					XMap ct = (XMap)fit.next();
					String id = ct.getString("id");
					if(id!=null)locks.add(id);
				}
			context.addJsonConfig(PROPERTITY_LOCK, locks);
		}
			
		XMap datas = view.getChild(PROPERTITY_DATAS); 
//		List<XMap> dataList = new ArrayList<XMap>(); 
		List list = null;
		if(datas != null){
			String ds = datas.getString(PROPERTITY_DATASOURCE, "");
			if(!"".equals(ds)){
				//从model中获取数据
				Object obj = model.get(ds);
				if(obj instanceof Map){
					list = new ArrayList();
					list.add(obj);
				}else {
					list = (List)model.get(ds);
				}
			}
			if(list == null || list.size() == 0) list = datas.getChilds();
			if(list != null){
				//TODO:干什么用的?
//					Iterator<XMap> dit = list.iterator();
//					while(dit.hasNext()){
//						XMap item = (XMap)dit.next();
//						Iterator it = new ArrayList(item.keySet()).iterator();
//						while(it.hasNext()){
//							String key = (String)it.next();
//							Object valueKey = item.get(key);
//							if(valueKey==null){
//								item.remove(key);
//							}
//						}
//						dataList.put(json);
//					}
				context.addJsonConfig(PROPERTITY_DATAS, list);
			}
		}
		//TODO:获取值列表
//			String lcode = dsc.getLookupCode();
//			if(lcode!=null){
//				ILookupCodeProvider provider = session.getLookupProvider();
//				if(provider!=null){
//					List llist = new ArrayList();
//					try {
//						llist = provider.getLookupList(session.getLanguage(), lcode);
//					} catch (Exception e) {
//						throw new IOException(e.getMessage());
//					}
//					if(llist!=null){
//						Iterator it = llist.iterator();
//						while(it.hasNext()){
//							JSONObject json = new JSONObject((CompositeMap)it.next());
//							dataList.put(json);					
//						}
//					}
//				}
//			}
		String queryDataSet = view.getString(PROPERTITY_QUERYDATASET);
		if(queryDataSet!=null)context.addJsonConfig("qds", queryDataSet);
		
		String queryUrl = view.getString(PROPERTITY_QUERYURL);
		if(queryUrl!=null)context.addJsonConfig("qurl", queryUrl);
		
		String submitUrl = view.getString(PROPERTITY_SUBMITURL);
		if(submitUrl!=null)context.addJsonConfig("surl", submitUrl);
		
		String bindTarget = view.getString(PROPERTITY_BINDTARGET);
		if(bindTarget!=null)context.addJsonConfig("bt", bindTarget);
		
		String bindName = view.getString(PROPERTITY_BINDNAME);
		if(bindTarget!=null)context.addJsonConfig("bn", bindName);
		
		boolean isAutoQuery = view.getBoolean(PROPERTITY_AUTO_QUERY,false);
		if(isAutoQuery)context.addJsonConfig("aq", isAutoQuery);
		
		Integer psize = view.getInt(PROPERTITY_PAGESIZE);
		if(psize!= null)context.addJsonConfig("psize", psize);
		
		boolean isAutoCreate = view.getBoolean(PROPERTITY_AUTO_CREATE,false);
		if(isAutoCreate)context.addJsonConfig("ac", isAutoCreate);
		
		boolean isSelectable = view.getBoolean(PROPERTITY_SELECTABLE,false);
		if(isSelectable)context.addJsonConfig("sb", isSelectable);
		
		String selectFun = view.getString(PROPERTITY_SELECT_FUNCTION);
		if(selectFun!=null)context.addJsonConfig("sft", selectFun);
		
		boolean checkDiry = view.getBoolean(PROPERTITY_CHECK_DIRTY,false);
		if(checkDiry)context.addJsonConfig(PROPERTITY_CHECK_DIRTY, checkDiry);
		
		String sortModel = view.getString(PROPERTITY_SORT_MODEL);
		if(sortModel!=null)context.addJsonConfig("sortModel", sortModel);
		
		String defaultSortField = view.getString(PROPERTITY_DEFAULT_SORT_FIELD);
		if(defaultSortField!=null)context.addJsonConfig("defaultSortField", defaultSortField);
		
		String defaultSortType = view.getString(PROPERTITY_DEFAULT_SORT_TYPE);
		if(defaultSortType!=null)context.addJsonConfig("defaultSortType", defaultSortType);		
		
		String loadingTip = view.getString(PROPERTITY_LOADING_TIP);
		if(loadingTip!=null)context.addJsonConfig(PROPERTITY_LOADING_TIP, loadingTip);
		
		String notFoundMessage = view.getString(PROPERTITY_NOT_FOUND_MESSAGE);
		if(notFoundMessage!=null)context.addJsonConfig(PROPERTITY_NOT_FOUND_MESSAGE, notFoundMessage);
		
		String notFoundCallback = view.getString(PROPERTITY_NOT_FOUND_CALLBACK);
		if(notFoundCallback!=null)context.addJsonConfig(PROPERTITY_NOT_FOUND_CALLBACK, notFoundCallback);
		
		String successTip = view.getString(PROPERTITY_SUCCESS_TIP);
		if(successTip!=null)context.addJsonConfig(PROPERTITY_SUCCESS_TIP, successTip);
		
		String selectModel = view.getString(PROPERTITY_SELECTION_MODEL);
		if (selectModel != null && !DEFAULT_SELECTION_MODEL.equals(selectModel))
			context.addJsonConfig("sm", selectModel);

	}
	
	@SuppressWarnings("unchecked")
	protected String build(SparkContext context){
		Map map = context.getMap();
		StringBuilder sb = new StringBuilder();
		sb.append("<script>\r");
		sb.append("new Spark.DataSet(").append(get(map,"config")).append(");\r");
		sb.append("</script>\r");
		return sb.toString();


	}

}
